package com.ssdp.interceptor;

import cn.hutool.core.bean.BeanUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ssdp.dto.UserDTO;
import com.ssdp.constant.RedisConstant;
import com.ssdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author syo 2319615164@qq.com
 * @description 登录信息刷新拦截器
 * @date 2024/3/14
 * @Copyright syo
 */
@Component
@Slf4j
public class RefreshTokenInterceptor implements HandlerInterceptor {

    private final ObjectMapper objectMapper = new ObjectMapper();

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1. 判断用户是否存在
        // UserDTO user = (UserDTO)request.getSession().getAttribute("user");
        String token = request.getHeader("authorization");

        // 2. 没有token用户未登录不刷新状态直接放行
        if(StringUtils.isEmpty(token)) {
            return true;
        }

        // 3. 有token则刷新状态
        Map<Object, Object> userMap = stringRedisTemplate.opsForHash()
                .entries(RedisConstant.LOGIN_USER_KEY + token);

        // 4. 有token且用户已经登录
        if(userMap != null && !userMap.isEmpty()) {
            UserDTO userDTO = BeanUtil.fillBeanWithMap(userMap, new UserDTO(), false);
            userDTO.setToken(token);
            UserHolder.saveUser(userDTO);
            stringRedisTemplate.expire(RedisConstant.LOGIN_USER_KEY + token, RedisConstant.LOGIN_USER_TTL, TimeUnit.MINUTES);

        // 5. 有token但是用户没有登录(或者长时间失效了)
        } else {
            // 保证ThreadLocal中确实没有用户了
            UserHolder.removeUser();
        }

        // 6. 刷新完登录状态则放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHolder.removeUser();
    }
}
